package com.mallotec.reb.localeplugin.utils

import android.app.Activity
import android.content.BroadcastReceiver
import android.content.IntentFilter
import android.os.Build
import android.util.Log
import android.content.Context

object BroadcastReceiverManager {

    private const val TAG = "ReceiverManager"

    private val receiverMap: HashMap<Activity, BroadcastReceiver> = HashMap()

    fun registerBroadcastReceiver(activity: Activity, receiver: BroadcastReceiver, intentFilter: IntentFilter) {
        if (receiverMap[activity] == null) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {
                activity.registerReceiver(receiver, intentFilter, Context.RECEIVER_NOT_EXPORTED)
            } else {
                activity.registerReceiver(receiver, intentFilter)
            }
            receiverMap[activity] = receiver
            Log.e(TAG, activity.localClassName + "BroadcastReceiver register")
        } else {
            Log.e(TAG, activity.localClassName + "BroadcastReceiver is already registered")
        }
    }

    fun unregisterBroadcastReceiver(activity: Activity) {
        receiverMap[activity]?.let {
            activity.unregisterReceiver(it)
            receiverMap.remove(activity)
            Log.e(TAG, activity.localClassName + "BroadcastReceiver unregister")
        } ?: Log.e(TAG, activity.localClassName + "BroadcastReceiver is already unregistered")
    }

    fun unregisterAllBroadcastReceiver() {
        for ((activity, receiver) in receiverMap) {
            activity.unregisterReceiver(receiver)
        }
        receiverMap.clear()
    }
}